package com.qhw.servlet;

import com.qhw.JdbcUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/qhwlogin")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String u = req.getParameter("u");//用户名
        String p = req.getParameter("p");//密码
        String c = req.getParameter("c");//验证码
        System.out.println("username = " + u);
        System.out.println("password = " + p);
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();

        HttpSession session = req.getSession();
        Object q = session.getAttribute("Q");
        boolean isTrue = c != null && c.equals(q)|| (c.equals(1));
        if (!isTrue) {
            writer.write("code is error");
            writer.flush();
            writer.close();
            return;
        }
        String sql6 = "select id from `user` where username = ? and `password` = MD5(?)";
        Long id = JdbcUtils.select(sql6, Long.class, u, p);
        if (id != null) {
            session.setAttribute("UID", id);
            resp.sendRedirect("/qhw/index.jsp");
        } else {
            resp.sendRedirect("/qhw/login.jsp");
        }

    }
}
